﻿#coding=utf-8
#Boa:FramePanel:PanelVoucher

import wx

import DlgCustomerChoice
import DlgPopupSupplier

from config import *
from product import *
from ctrlAider import *

from MyListCtrl import MyListCtrlOrderAmountAllocted

import kit
from ConfTool27 import conf
[Type_Customer, Type_Supplier] = [i for i in range(2)]

[wxID_PANELVOUCHER, wxID_PANELVOUCHERBTNAUTOALLOCATE, 
 wxID_PANELVOUCHERBTNCANCEL, wxID_PANELVOUCHERBTNDAYAFTER, 
 wxID_PANELVOUCHERBTNDAYBEFORE, wxID_PANELVOUCHERBTNOK, 
 wxID_PANELVOUCHERBTNREFRESH, wxID_PANELVOUCHERBTNSHOWPEER, 
 wxID_PANELVOUCHERCBPAYWAY, wxID_PANELVOUCHERCBSTAFF, 
 wxID_PANELVOUCHERCHECKACCOUNT, wxID_PANELVOUCHERCHOICESHOW, 
 wxID_PANELVOUCHERCOMBOSUBJECT, wxID_PANELVOUCHERDATEBILL, 
 wxID_PANELVOUCHERDATECHECK, wxID_PANELVOUCHERSTATICTEXT1, 
 wxID_PANELVOUCHERSTATICTEXT2, wxID_PANELVOUCHERSTATICTEXT3, 
 wxID_PANELVOUCHERSTATICTEXT4, wxID_PANELVOUCHERSTATICTEXT5, 
 wxID_PANELVOUCHERSTDEBT, wxID_PANELVOUCHERTCDEBT, wxID_PANELVOUCHERTCMEMO, 
 wxID_PANELVOUCHERTCMONEY, wxID_PANELVOUCHERTCPARTNER, 
 wxID_PANELVOUCHERTCUNALLOCATED, wxID_PANELVOUCHERTCVOUCHERID, 
 wxID_PANELVOUCHERTDATE, wxID_PANELVOUCHERTDEBT, wxID_PANELVOUCHERTMEMO, 
 wxID_PANELVOUCHERTMONEY, wxID_PANELVOUCHERTPARTNER, wxID_PANELVOUCHERTPAYWAY, 
 wxID_PANELVOUCHERTSTAFF, wxID_PANELVOUCHERTSUBJECT, wxID_PANELVOUCHERTTITLE, 
 wxID_PANELVOUCHERTVOUCHERID, 
] = [wx.NewId() for _init_ctrls in range(37)]

class PanelVoucher(wx.Panel):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Panel.__init__(self, id=wxID_PANELVOUCHER, name=u'PanelVoucher',
              parent=prnt, pos=wx.Point(610, 260), size=wx.Size(1202, 668),
              style=wx.TAB_TRAVERSAL)
        self.SetClientSize(wx.Size(1186, 630))
        self.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              u'\u6977\u4f53_GB2312'))
        self.SetBackgroundColour(wx.Colour(183, 209, 173))

        self.tTitle = wx.StaticText(id=wxID_PANELVOUCHERTTITLE,
              label=u'\u4ed8\u6b3e\u5355', name=u'tTitle', parent=self,
              pos=wx.Point(240, 32), size=wx.Size(63, 20), style=0)
        self.tTitle.SetFont(wx.Font(15, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              u'\u6977\u4f53_GB2312'))

        self.tVoucherId = wx.StaticText(id=wxID_PANELVOUCHERTVOUCHERID,
              label=u'\u5355\u53f7\uff1a', name=u'tVoucherId', parent=self,
              pos=wx.Point(416, 32), size=wx.Size(64, 16), style=0)

        self.tcVoucherId = wx.StaticText(id=wxID_PANELVOUCHERTCVOUCHERID,
              label=u'P(GK)F-20140516-0001', name=u'tcVoucherId', parent=self,
              pos=wx.Point(496, 32), size=wx.Size(180, 16), style=0)

        self.dateBill = wx.DatePickerCtrl(id=wxID_PANELVOUCHERDATEBILL,
              name=u'dateBill', parent=self, pos=wx.Point(488, 168),
              size=wx.Size(136, 22), style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)
        self.dateBill.SetLabel(u'2013-11-27')
        self.dateBill.SetValue(wx.DateTimeFromDMY(27, 10, 2013, 0, 0, 0))
        self.dateBill.SetWindowVariant(wx.WINDOW_VARIANT_NORMAL)
        self.dateBill.Bind(wx.EVT_DATE_CHANGED, self.OnDateBillDateChanged,
              id=wxID_PANELVOUCHERDATEBILL)

        self.tDate = wx.StaticText(id=wxID_PANELVOUCHERTDATE,
              label=u'\u6536\u6b3e\u65e5\u671f', name=u'tDate', parent=self,
              pos=wx.Point(408, 176), size=wx.Size(68, 16), style=0)

        self.btnShowPeer = wx.Button(id=wxID_PANELVOUCHERBTNSHOWPEER,
              label=u'+', name=u'btnShowPeer', parent=self, pos=wx.Point(384,
              88), size=wx.Size(24, 26), style=0)
        self.btnShowPeer.Bind(wx.EVT_BUTTON, self.OnBtnShowPeerButton,
              id=wxID_PANELVOUCHERBTNSHOWPEER)

        self.tcPartner = wx.TextCtrl(id=wxID_PANELVOUCHERTCPARTNER,
              name=u'tcPartner', parent=self, pos=wx.Point(176, 88),
              size=wx.Size(208, 24), style=0, value=u'')

        self.tPartner = wx.StaticText(id=wxID_PANELVOUCHERTPARTNER,
              label=u'\u9009\u62e9\u5355\u4f4d\uff1a', name=u'tPartner',
              parent=self, pos=wx.Point(88, 96), size=wx.Size(85, 16), style=0)

        self.tDebt = wx.StaticText(id=wxID_PANELVOUCHERTDEBT,
              label=u'\u603b\u6b20\u6b3e\uff1a', name=u'tDebt', parent=self,
              pos=wx.Point(88, 136), size=wx.Size(68, 16), style=0)

        self.tcDebt = wx.TextCtrl(id=wxID_PANELVOUCHERTCDEBT, name=u'tcDebt',
              parent=self, pos=wx.Point(176, 128), size=wx.Size(128, 24),
              style=0, value=u'0.0')
        self.tcDebt.SetEditable(False)
        self.tcDebt.Enable(False)

        self.tcMoney = wx.TextCtrl(id=wxID_PANELVOUCHERTCMONEY, name=u'tcMoney',
              parent=self, pos=wx.Point(176, 168), size=wx.Size(128, 24),
              style=0, value=u'0.0')
        self.tcMoney.Bind(wx.EVT_TEXT, self.OnTcMoneyText,
              id=wxID_PANELVOUCHERTCMONEY)

        self.tMoney = wx.StaticText(id=wxID_PANELVOUCHERTMONEY,
              label=u'\u4ed8\u6b3e\u91d1\u989d\uff1a', name=u'tMoney',
              parent=self, pos=wx.Point(88, 176), size=wx.Size(85, 16),
              style=0)

        self.tPayWay = wx.StaticText(id=wxID_PANELVOUCHERTPAYWAY,
              label=u'\u4ed8\u6b3e\u8d26\u6237\uff1a', name=u'tPayWay',
              parent=self, pos=wx.Point(88, 216), size=wx.Size(85, 16),
              style=0)

        self.cbPayWay = wx.ComboBox(choices=[], id=wxID_PANELVOUCHERCBPAYWAY,
              name=u'cbPayWay', parent=self, pos=wx.Point(176, 208),
              size=wx.Size(130, 24), style=0, value=u'')
        self.cbPayWay.SetLabel(u'')

        self.staticText3 = wx.StaticText(id=wxID_PANELVOUCHERSTATICTEXT3,
              label=u'(\u6ce8\u610f\uff1a\u8981\u624b\u52a8\u6d88\u9664\u4e0eexcel\u5bfc\u5165\u91cd\u590d\u7684\u8bb0\u5f55)',
              name='staticText3', parent=self, pos=wx.Point(808, 144),
              size=wx.Size(335, 16), style=0)

        self.tStaff = wx.StaticText(id=wxID_PANELVOUCHERTSTAFF,
              label=u'\u7ecf\u529e\u4eba\uff1a', name=u'tStaff', parent=self,
              pos=wx.Point(792, 56), size=wx.Size(72, 14), style=0)

        self.cbStaff = wx.ComboBox(choices=[], id=wxID_PANELVOUCHERCBSTAFF,
              name=u'cbStaff', parent=self, pos=wx.Point(888, 48),
              size=wx.Size(138, 24), style=0, value=u'')
        self.cbStaff.Enable(False)

        self.tcUnallocated = wx.TextCtrl(id=wxID_PANELVOUCHERTCUNALLOCATED,
              name=u'tcUnallocated', parent=self, pos=wx.Point(464, 280),
              size=wx.Size(104, 24), style=0, value=u'0.0')
        self.tcUnallocated.SetEditable(False)
        self.tcUnallocated.Enable(False)

        self.staticText2 = wx.StaticText(id=wxID_PANELVOUCHERSTATICTEXT2,
              label=u'\u672a\u5206\u914d\u91d1\u989d\uff1a', name='staticText2',
              parent=self, pos=wx.Point(360, 288), size=wx.Size(102, 16),
              style=0)

        self.btnRefresh = wx.Button(id=wxID_PANELVOUCHERBTNREFRESH,
              label=u'\u5237\u65b0\u5355\u636e', name=u'btnRefresh',
              parent=self, pos=wx.Point(208, 248), size=wx.Size(93, 26),
              style=0)
        self.btnRefresh.Bind(wx.EVT_BUTTON, self.OnBtnRefreshButton,
              id=wxID_PANELVOUCHERBTNREFRESH)

        self.staticText1 = wx.StaticText(id=wxID_PANELVOUCHERSTATICTEXT1,
              label=u'\u9009\u62e9\u6307\u5b9a\u5355\u636e\uff1a',
              name='staticText1', parent=self, pos=wx.Point(88, 256),
              size=wx.Size(119, 16), style=0)

        self.btnAutoAllocate = wx.Button(id=wxID_PANELVOUCHERBTNAUTOALLOCATE,
              label=u'\u81ea\u52a8\u5206\u914d\u5269\u4f59\u91d1\u989d',
              name=u'btnAutoAllocate', parent=self, pos=wx.Point(576, 280),
              size=wx.Size(144, 26), style=0)
        self.btnAutoAllocate.Bind(wx.EVT_BUTTON, self.OnBtnAutoAllocateButton,
              id=wxID_PANELVOUCHERBTNAUTOALLOCATE)

        self.tcMemo = wx.TextCtrl(id=wxID_PANELVOUCHERTCMEMO, name=u'tcMemo',
              parent=self, pos=wx.Point(176, 536), size=wx.Size(448, 24),
              style=0, value=u'')

        self.tMemo = wx.StaticText(id=wxID_PANELVOUCHERTMEMO,
              label=u'\u5907\u6ce8\u4fe1\u606f\uff1a', name=u'tMemo',
              parent=self, pos=wx.Point(88, 544), size=wx.Size(85, 16),
              style=0)

        self.btnOK = wx.Button(id=wxID_PANELVOUCHERBTNOK,
              label=u'\u4fdd\u5b58\u4fee\u6539', name=u'btnOK', parent=self,
              pos=wx.Point(408, 568), size=wx.Size(75, 24), style=0)
        self.btnOK.Bind(wx.EVT_BUTTON, self.OnBtnOKButton,
              id=wxID_PANELVOUCHERBTNOK)

        self.btnCancel = wx.Button(id=wxID_PANELVOUCHERBTNCANCEL,
              label=u'\u9000\u51fa', name=u'btnCancel', parent=self,
              pos=wx.Point(568, 568), size=wx.Size(75, 24), style=0)
        self.btnCancel.Bind(wx.EVT_BUTTON, self.OnBtnCancelButton,
              id=wxID_PANELVOUCHERBTNCANCEL)

        self.choiceShow = wx.Choice(choices=[], id=wxID_PANELVOUCHERCHOICESHOW,
              name=u'choiceShow', parent=self, pos=wx.Point(88, 280),
              size=wx.Size(216, 24), style=0)
        self.choiceShow.Bind(wx.EVT_CHOICE, self.OnChoiceShowChoice,
              id=wxID_PANELVOUCHERCHOICESHOW)

        self.tSubject = wx.StaticText(id=wxID_PANELVOUCHERTSUBJECT,
              label=u'\u4f1a\u8ba1\u79d1\u76ee\uff1a', name=u'tSubject',
              parent=self, pos=wx.Point(792, 96), size=wx.Size(85, 16),
              style=0)

        self.comboSubject = wx.ComboBox(choices=[],
              id=wxID_PANELVOUCHERCOMBOSUBJECT, name=u'comboSubject',
              parent=self, pos=wx.Point(888, 88), size=wx.Size(150, 24),
              style=0, value=u'')
        self.comboSubject.SetLabel(u'')

        self.checkAccount = wx.CheckBox(id=wxID_PANELVOUCHERCHECKACCOUNT,
              label=u'\u6dfb\u52a0\u4e00\u6761<\u8d44\u91d1\u660e\u7ec6>\uff0c\u7f16\u8f91\u6a21\u5f0f\u9ed8\u8ba4\u4e0d\u6dfb\u52a0',
              name=u'checkAccount', parent=self, pos=wx.Point(792, 128),
              size=wx.Size(376, 16), style=0)
        self.checkAccount.SetValue(True)

        self.staticText4 = wx.StaticText(id=wxID_PANELVOUCHERSTATICTEXT4,
              label=u'\u5bf9\u8d26\u65e5\u671f', name='staticText4',
              parent=self, pos=wx.Point(408, 216), size=wx.Size(68, 16),
              style=0)

        self.dateCheck = wx.DatePickerCtrl(id=wxID_PANELVOUCHERDATECHECK,
              name=u'dateCheck', parent=self, pos=wx.Point(488, 208),
              size=wx.Size(136, 24), style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)

        self.btnDayBefore = wx.Button(id=wxID_PANELVOUCHERBTNDAYBEFORE,
              label=u'\u524d\u4e00\u5929', name=u'btnDayBefore', parent=self,
              pos=wx.Point(488, 238), size=wx.Size(64, 29), style=0)
        self.btnDayBefore.Bind(wx.EVT_BUTTON, self.OnBtnDayBeforeButton,
              id=wxID_PANELVOUCHERBTNDAYBEFORE)

        self.btnDayAfter = wx.Button(id=wxID_PANELVOUCHERBTNDAYAFTER,
              label=u'\u540e\u4e00\u5929', name=u'btnDayAfter', parent=self,
              pos=wx.Point(560, 238), size=wx.Size(64, 29), style=0)
        self.btnDayAfter.Bind(wx.EVT_BUTTON, self.OnBtnDayAfterButton,
              id=wxID_PANELVOUCHERBTNDAYAFTER)

        self.staticText5 = wx.StaticText(id=wxID_PANELVOUCHERSTATICTEXT5,
              label=u'\u603b\u6b20\u6b3e\uff1a', name='staticText5',
              parent=self, pos=wx.Point(312, 120), size=wx.Size(68, 16),
              style=0)
        self.staticText5.SetForegroundColour(wx.Colour(255, 0, 0))

        self.stDebt = wx.StaticText(id=wxID_PANELVOUCHERSTDEBT, label=u'-/-',
              name=u'stDebt', parent=self, pos=wx.Point(312, 144),
              size=wx.Size(27, 16), style=0)
        self.stDebt.SetForegroundColour(wx.Colour(255, 0, 0))
        self.stDebt.Bind(wx.EVT_LEFT_DCLICK, self.OnStLeftDclick)

    def __init__(self, parent, type):
        self._init_ctrls(parent)
        
        self.initState()
        self.initType(type)    
        self.myInit()
        self._initChoice()
        
        self.m_bSingleOrder = False
        #self.btnMakeAccountDetail.Enable(False)

        b_boss = conf.getint('permission', 'boss', 0)
        self.btnOK.Show(True if b_boss==1 else False)
        
    def _initChoice(self):
        self.showAll = self.choiceShow.Append(u'显示全部')
        self.showUnpaid = self.choiceShow.Append(u'只显示未付款单据')
        self.showAlloct = self.choiceShow.Append(u'只显示分配有金额的单据')
        self.choiceShow.SetSelection(self.showUnpaid)
        
        self.showState = {self.showAll:'all', self.showUnpaid:'unpaid', self.showAlloct:'alloct'}
    
    def initType(self, type):
        self.curType = type
        if(type == Type_Customer):
            self.ClsPeer = CDataCustomer
            self.ClsOrder = CDataSaleOrder
            self.ClsVoucher = CDataVoucher
            self.ClsFund = CRelFundCustomer
            
            self.pWin = DlgCustomerChoice.create(self)
            self.tcPeer = MyPopupTextCtrlDecorator(self.tcPartner, self.pWin)
            
        elif(type == Type_Supplier):
            self.ClsPeer = CDataSupplier
            self.ClsOrder = CDataPurOrder
            self.ClsVoucher = CDataVoucherSupplier
            self.ClsFund = CRelFundSupplier
            
            self.pWin = DlgPopupSupplier.create(self)
            self.tcPeer = MyPopupTextCtrlDecorator(self.tcPartner, self.pWin)
            
##            self.tPartner.SetLabel(u'供货商：')
##            self.tMoney.SetLabel(u'付款金额：')
##            self.tPayWay.SetLabel(u'付款方式：')
    
    def initState(self):
        self.STATE_NEW = 0
        self.STATE_MODIFY = 1
        self.curState = self.STATE_NEW
        
        self.editedVoucherId = ''
            
    def myInit(self):
        self.m_peer = None
        self.accountDetailObj = None
        
        self.dateBill.SetValue(wx.DateTime.Today())
        #self.dateCheck.SetValue(wx.DateTime.Today())
        self.refreshId()
        
        self.cb = MyComboBoxDecorator(self.cbPayWay, CDataAccount, CDataAccount.COL_BRIEFNAME, only_enable_account)
        self.cb.refresh()
        # Cancel defaultAccount in case we forget to change it
        #self.cb.SetValue(CDataAccount.getDefAccount())
        
        self.cbHandler = MyComboBoxDecorator(self.cbStaff, CDataStaff, CDataStaff.COL_NAME)
        self.cbHandler.refresh()
        self.cbHandler.SetValue(Cfg.getCurUser().getValue(CDataStaff.COL_NAME))
        
        self.cbSubject = MyComboBoxDecorator(self.comboSubject, CDataAccountSubject, CDataAccountSubject.fi_name)
        self.cbSubject.refresh()
        
        if(self.curType == Type_Customer):
            self.cbSubject.SetValue(CDataAccountSubject.getDefName())
        elif(self.curType == Type_Supplier):
            self.cbSubject.SetValue(CDataAccountSubject.getDefName(False))
        else:
            print (u'未知类型', self.curType)    
                     
        self.lc = MyListCtrlOrderAmountAllocted(self, self.ClsPeer)
        self.lc.SetSize(wx.Size(1000 if self.curType == Type_Customer else 600, 215))
        self.lc.Move(wx.Point(88, 310))
        self.lc.Bind(wx.EVT_LEFT_DCLICK, self.OnMenuAlloct)
        
        item = self.lc.menu.Append(-1, u'修改分配金额')
        self.Bind(wx.EVT_MENU, self.OnMenuAlloct, item)   
        
        item = self.lc.menu.Append(-1, u'清除已分配金额')
        self.Bind(wx.EVT_MENU, self.OnMenuClear, item)
        
        self.lc.menu.AppendSeparator()      
        
        item = self.lc.menu.Append(-1, u'修改优惠金额')
        self.Bind(wx.EVT_MENU, self.OnMenuDiscount, item)

        self.lc.menu.AppendSeparator()      
        
        item = self.lc.menu.Append(-1, u'自动优惠余额')
        self.Bind(wx.EVT_MENU, self.OnMenuAutoDiscount, item)
        
        #self.lc.menu.AppendSeparator()  
     
    def disableMoneyEditor(self):
        self.tcMoney.Disable()
        self.cbPayWay.Disable()
        self.dateBill.Disable()
        #self.dateCheck.Disable()
           
    def isModify(self):
        return self.curState == self.STATE_MODIFY
    
    def setFocusMoney(self):
        '''焦点'''
        self.tcMoney.SetInsertionPointEnd()
        self.tcMoney.SetSelection(-1, -1)
        self.tcMoney.SetFocus()
     
    def refreshId(self):
        if self.isModify():
            # 150902 编辑模式禁止修改ID，否则ID变化会导致相关表要求同步修改，复杂度高，健壮性差
            return
        
        date = self.dateBill.GetValue().Format('%Y%m%d')
        self.tcVoucherId.SetLabel(self.ClsVoucher.newBillId(date))
    
    def getMoney(self):
        print("'",self.tcMoney.GetValue(),"'")
        return float(self.tcMoney.GetValue())
    
    def resetUnallocated(self):
        self.tcUnallocated.SetValue(str(self.getMoney()-self.lc.getAlloctSum()))
    
    def setSelectPeer(self, obj, refreshBill=True):
        self.m_peer = obj
        
        peerName = obj.getValue(obj.COL_NAME)
        self.tcPeer.ChangeValue(peerName)
        
        debt = obj.getDebt()
        self.tcDebt.SetValue(kit.myStr(debt))
        self.stDebt.SetLabel(kit.myStr(debt))
                
        title = u'【款】%s' %peerName
        book = self.GetParent()
        self.GetParent().SetPageText(book.GetSelection(), title)
        
        if(refreshBill):
            self.refreshList()
            #self.lc.refresh({'peerId':self.m_peer.getValue(self.m_peer.COL_ID)})
            #self.lc.SortListItems(0, 0)

        self.setFocusMoney()
    
    def setSelectBill(self, billId):
        billObj = self.ClsOrder.getFirstInstance({self.ClsOrder.COL_ID:billId})
        peerId = billObj.getValue(billObj.COL_PEERID)
        peerObj = self.ClsPeer.getFirstInstance({self.ClsPeer.COL_ID:peerId})
        
        #unpaid = billObj.getValue(billObj.COL_UNPAID)
        unpaid = billObj.getUnpaid()
        if (unpaid <= 0.0):
            self.setSelectPeer(peerObj)
        else:
            msg = u'是否针对<%s>付款\n'\
                    u'--选是，为该付款单付款\n'\
                    u'--选否，为<%s>增加付款单' %(billId, peerObj.getValue(peerObj.COL_NAME))
            dlg = wx.MessageDialog(self, msg,
                                    u'提示', wx.YES_NO|wx.ICON_QUESTION)
            
            if(dlg.ShowModal() == wx.ID_YES):
                self.setSelectPeer(peerObj, False)
                
                unpaid = billObj.getUnpaid()
                self.tDebt.SetLabel(u'订单欠款:')
                self.tcDebt.SetValue(kit.myStr(unpaid))
                self.tcMoney.SetValue(kit.myStr(unpaid))
                memo = u'为%s收款' %(billId)
                self.tcMemo.SetValue(memo)
                
                self.lc.appendBill(billObj)
                self.lc.setAlloct(0, unpaid)
                self.resetUnallocated()
                # 修改付款金额时，自动分配金额，未分配金额随之变化，以减少操作
                self.m_bSingleOrder = True 
                
            else:
                self.setSelectPeer(peerObj)
                
        self.setFocusMoney()
    
    def deletePreVoucher(self):
        self.ClsVoucher.deepDelData(self.editedVoucherId)
        
    def setEditVoucher(self, voucherId):
        print(u'编辑voucher', voucherId)
        self.curState = self.STATE_MODIFY
        self.editedVoucherId = voucherId
        
        # 编辑模式默认不添加<资金明细>
        self.checkAccount.SetValue(False)
        
        accountDetailObj = CDataAccountDetail.getFirstInstance({CDataAccountDetail.COL_FUNDID:voucherId})
        if accountDetailObj:
            msg = u'该单据已经关联到资金账户变动明细，是否保留关联关系\n'\
                    u'  - 是，保留关联，并禁止修改金额、账户、日期\n'\
                    u'  - 否，接触关联，并允许修改金额、账户、日期'
            
            dlg = wx.MessageDialog(self, msg,u'提示',wx.YES_NO|wx.ICON_QUESTION)
            if (dlg.ShowModal() == wx.ID_YES):
                self.disableMoneyEditor()
                self.accountDetailObj = accountDetailObj
            else:
                accountDetailObj.setValue(accountDetailObj.COL_FUNDID, None)
                accountDetailObj.update()

            self.cbSubject.SetValue(accountDetailObj.getSubjectName())
        else:
            msg = u'该单据尚未关联到资金账户变动明细，可以选择添加一条变动明细或从资金账户中进行关联'
            dlg = wx.MessageDialog(self, msg, u'提示', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
        
        self.choiceShow.SetSelection(self.showAlloct)
        
        voucherObj = self.ClsVoucher.getFirstInstance({self.ClsVoucher.iId:voucherId})
        
        peerId = voucherObj.getValue(voucherObj.iPeerId) 
        peerObj = self.ClsPeer.getFirstInstance({self.ClsPeer.COL_ID:peerId})
        
        money = voucherObj.getValue(voucherObj.iMoney)
        memo = voucherObj.getValue(voucherObj.iMemo)
                
        date = voucherObj.getValue(voucherObj.iDate)
        if (isinstance(date, str) or isinstance(date, unicode)):
            import datetime
            date = datetime.datetime.strptime(date, '%Y-%m-%d')
        date = wx.DateTimeFromDMY(date.day, date.month-1, date.year,0,0,0)

        dateCheck = voucherObj.getValue(voucherObj.iCheckDate)
        if (isinstance(dateCheck, str) or isinstance(dateCheck, unicode)):
            import datetime
            dateCheck = datetime.datetime.strptime(dateCheck, '%Y-%m-%d')
        dateCheck = wx.DateTimeFromDMY(dateCheck.day, dateCheck.month-1, dateCheck.year,0,0,0)
        
        hId = voucherObj.getValue(voucherObj.iHandlerId)
        hObj = CDataStaff.getFirstInstance({CDataStaff.COL_ID:hId})
        hName = hObj.getValue(CDataStaff.COL_NAME)
        
        accountId = voucherObj.getValue(voucherObj.COL_ACCOUNTID)
        accountObj = CDataAccount.getFirstInstance({CDataAccount.COL_ID:accountId})
        accountName = accountObj.getValue(CDataAccount.COL_BRIEFNAME)
        
        # 发送数据到界面
        self.setSelectPeer(peerObj)
        
        self.tcVoucherId.SetLabel(voucherId)
        self.dateBill.SetValue(date)
        self.dateCheck.SetValue(dateCheck)
        self.cb.SetValue(accountName)
        self.cbHandler.SetValue(hName)
        self.tcMoney.SetValue(str(money))
        self.tcMemo.SetValue(memo)
        
        self.lc.attachVoucher(voucherObj)
        
        self.resetUnallocated()
        self.setFocusMoney()
    
    def saveVoucher(self):
        id = self.tcVoucherId.GetLabel()
        peerId = self.m_peer.getValue(self.m_peer.COL_ID)
        
        accountObj = self.cb.getSelectObj()
        accountId = accountObj.getValue(CDataAccount.COL_ID)
        
        money = float(self.tcMoney.GetValue())
        date = self.dateBill.GetValue().Format('%Y-%m-%d')
        dateChk = self.dateCheck.GetValue().Format('%Y-%m-%d')
        handlerId = self.cbHandler.getSelectObj().getValue(CDataStaff.COL_ID)
        recorderID = Cfg.getCurUser().getValue(CDataStaff.COL_ID)      
        memo = self.tcMemo.GetValue()
        
        data = {self.ClsVoucher.iId:id, 
                self.ClsVoucher.iPeerId:peerId, 
                self.ClsVoucher.iAccountId:accountId,
                self.ClsVoucher.iMoney:money, 
                self.ClsVoucher.iDate:date,
                self.ClsVoucher.iCheckDate:dateChk,
                self.ClsVoucher.iHandlerId:handlerId,
                self.ClsVoucher.iRecorderId:recorderID, 
                self.ClsVoucher.iMemo:memo}
        obj = self.ClsVoucher.factory(False)
        obj.setMulFieldVal(data)
        obj.insert()
     
    def saveFund(self):
##        if (self.grid.GetNumberRows() == 1):
##            unpaid = float(self.grid.GetCellValue(0, self.COL_UNPAID))
##            alloct = self.getAlloct(0)
##            remain = unpaid - alloct
##            if (remain > 0.0 and alloct > 0.0):
##                msg = u'该订单仍欠 %g 元，是否对该订单优惠 %g 元？' %(remain, remain)
##                dlg = wx.MessageDialog(self, msg,u'提示',wx.YES_NO|wx.ICON_QUESTION)
##                if (dlg.ShowModal() == wx.ID_YES):
##                    #self.grid.SetCellValue(0, self.COL_UNPAID, kit.myStr(0.0))
##                    self.grid.SetCellValue(0, self.COL_DISCOUNT, kit.myStr(remain))
            
        voucherId =  self.tcVoucherId.GetLabel()
        for row in range(self.lc.GetItemCount()):
            alloct = self.lc.getAlloct(row)
            if (abs(alloct) < 0.001):
                continue
            
            billId = self.lc.getOrderId(row)
            data = {self.ClsFund.COL_BILLID:billId, 
                    self.ClsFund.COL_VOUCHERID:voucherId, 
                    self.ClsFund.COL_MONEY:alloct}
            obj = self.ClsFund.factory()
            obj.setMulFieldVal(data)
            obj.insert()
    
    def setAccountDetail(self, id):
        accountDetailObj = CDataAccountDetail.getFirstInstance({CDataAccountDetail.COL_ID:id})
        accountId = accountDetailObj.getValue(accountDetailObj.COL_ACCOUNTID)
        accountObj = CDataAccount.getFirstInstance({CDataAccount.COL_ID:accountId})
        
        money = accountDetailObj.getValue(accountDetailObj.COL_MONEY)
        if (money < 0.0):
            if(self.curType != Type_Supplier):
                msg = u'该款项为支出，应该是向供货商付款，但是单据为收款单，请注意是否出错'
                dlg = wx.MessageDialog(self, msg,
                                    u'提示', wx.OK|wx.ICON_INFORMATION)
            
                dlg.ShowModal()
            else:
                money = -money
                    
        self.tcMoney.SetValue(kit.myStr(money))
        self.cb.SetValue(accountObj.getValue(accountObj.COL_BRIEFNAME))
        
        date = accountDetailObj.getValue(CDataAccountDetail.COL_DATE)
        self.dateBill.SetValue(wx.DateTimeFromDMY(date.day, date.month-1, date.year,0,0,0))
        self.refreshId()
        
        self.cbSubject.SetValue(accountDetailObj.getSubjectName())
        
        self.tcMoney.Disable()
        self.cbPayWay.Disable()
        self.dateBill.Disable()
        
        self.accountDetailObj = accountDetailObj
                
    def updateAccountDetail(self):
        '''self.accountDetailObj存在时(通过账户明细新建付款)，对其进行更新'''
        self.accountDetailObj.setValue(self.accountDetailObj.COL_FUNDID, self.tcVoucherId.GetLabel())
        memo = self.accountDetailObj.getValue(self.accountDetailObj.COL_MEMO)
        memo += self.tcPeer.GetValue()
        self.accountDetailObj.setValue(self.accountDetailObj.COL_MEMO, memo)
        #self.accountDetailObj.setValue(self.accountDetailObj.COL_TIME, datetime.datetime.now())
        
        subjectObj = self.cbSubject.getSelectObj()
        if subjectObj:
            self.accountDetailObj.setValue(self.accountDetailObj.COL_SUBJECT, 
                        subjectObj.getValue(subjectObj.fi_id))
        
        self.accountDetailObj.update()
    
    def getAccountId(self):
        accountObj = self.cb.getSelectObj()
        return accountObj.getValue(CDataAccount.COL_ID)
                
    def makeAccountDetail(self):
        '''新建一条交易记录'''
        money = float(self.tcMoney.GetValue())
        if (self.curType == Type_Supplier):
            money = -money
            
        date = self.dateBill.GetValue().Format('%Y-%m-%d') 
        sysmemo = u'  【会款单：%s】' %self.tcVoucherId.GetLabel()
        
        data = {CDataAccountDetail.COL_ACCOUNTID:self.getAccountId(),
                CDataAccountDetail.COL_DATE:date,
                CDataAccountDetail.COL_MONEY:money,
                CDataAccountDetail.COL_FUNDID:self.tcVoucherId.GetLabel(),
                CDataAccountDetail.COL_MEMO:self.tcPeer.GetValue(),
                CDataAccountDetail.COL_SYSMEMO:sysmemo,
                CDataAccountDetail.COL_TIME:datetime.datetime.now(),
                CDataAccountDetail.COL_SUBJECT:1}
        
        subjectObj = self.cbSubject.getSelectObj()
        if subjectObj:
            data[CDataAccountDetail.COL_SUBJECT] = subjectObj.getValue(subjectObj.fi_id)
        else:
            data[CDataAccountDetail.COL_SUBJECT] = None # 需要重构缺省值
                                
        obj = CDataAccountDetail.factory()
        obj.setMulFieldVal(data)
        return obj.insert()
                   
    def quit(self, doQuit=True):
        if doQuit:    
            book = self.GetParent()
            book.DeletePage(book.GetSelection())
        return True
    
    def doClose(self, doQuit=True):
        if (self.btnOK.IsEnabled()):
            msg = u'是否继续退出当前业务操作?'
            dlg = wx.MessageDialog(self, msg,u'提示',wx.YES_NO|wx.ICON_QUESTION)
            if(dlg.ShowModal() == wx.ID_NO):
                return False
        return self.quit(doQuit)
             
    def OnMenuClear(self, event):
        self.lc.clearAlloct()
        self.resetUnallocated()
    
    def OnMenuAlloct(self, event):
        item = self.lc.GetNextItem(-1, state = wx.LIST_STATE_SELECTED)
        if (item == -1):
            return
        
        msg = u'修改分配金额：'
        caption = u'修改分配金额'
        val = self.lc.GetItem(item, self.lc.iAlloct).GetText()
        
        dlg = wx.TextEntryDialog(self, msg, caption, val)
        if (dlg.ShowModal() == wx.ID_OK):
            if(kit.myFloatStrTest(dlg.GetValue())):
                # 会导致无法输入负金额
                # val = float(dlg.GetValue())
                # if (val > float(self.tcUnallocated.GetValue())):
                #     dlg = wx.MessageDialog(self, u'输入错误：分配金额大于可分配金额',u'提示',wx.OK|wx.ICON_ERROR)
                #     dlg.ShowModal()
                #     return
                self.lc.setAlloct(item, float(dlg.GetValue()))
                
                self.resetUnallocated()
            
    def OnMenuDiscount(self, event):
        item = self.lc.GetNextItem(-1, state = wx.LIST_STATE_SELECTED)
        if (item == -1):
            return
        
        msg = u'修改优惠金额'
        caption = u'修改优惠金额'
        val = self.lc.GetItem(item, self.lc.iDiscount).GetText()
        
        dlg = wx.TextEntryDialog(self, msg, caption, val)
        if (dlg.ShowModal() == wx.ID_OK):
            if(kit.myFloatStrTest(dlg.GetValue())):
                val = float(dlg.GetValue())
                self.lc.setDiscount(item, val)
                
                # 保存<优惠金额>到数据库
                billId = self.lc.GetItem(item, self.lc.iBillId).GetText()
                billObj = self.ClsOrder.getFirstInstance({self.ClsOrder.COL_ID:billId})
                billObj.setValue(self.ClsOrder.COL_DISCOUNT, val)
                billObj.update()
          

    def OnMenuAutoDiscount(self, event):
        item = self.lc.GetNextItem(-1, state = wx.LIST_STATE_SELECTED)
        if (item == -1):
            return
        
        # msg = u'修改优惠金额'
        # caption = u'修改优惠金额'
        # val = self.lc.GetItem(item, self.lc.iDiscount).GetText()
        
        # dlg = wx.TextEntryDialog(self, msg, caption, val)
        # if (dlg.ShowModal() == wx.ID_OK):
        #     if(kit.myFloatStrTest(dlg.GetValue())):
        #         val = float(dlg.GetValue())
        if (True):
            if(True):
                val = float(self.lc.GetItem(item, self.lc.iUnpaid).GetText()) + float (self.lc.GetItem(item, self.lc.iDiscount).GetText())
                self.lc.setDiscount(item, val)
                
                # 保存<优惠金额>到数据库
                billId = self.lc.GetItem(item, self.lc.iBillId).GetText()
                billObj = self.ClsOrder.getFirstInstance({self.ClsOrder.COL_ID:billId})
                billObj.setValue(self.ClsOrder.COL_DISCOUNT, val)
                billObj.update()


    def OnDateBillDateChanged(self, event):
        self.refreshId()
        if (self.curState == self.STATE_NEW):
            self.dateCheck.SetValue(self.dateBill.GetValue())

    def OnBtnShowPeerButton(self, event):
        self.tcPeer.resetPopupWinPos()
        self.pWin.Show()

    def OnTcMoneyText(self, event):
        if (self.m_bSingleOrder):
            self.lc.setAlloct(0, self.getMoney())
        
        self.resetUnallocated()

    def refreshList(self):
        filter = {'peerId':self.m_peer.getValue(self.m_peer.COL_ID)}
        if (self.editedVoucherId != ''):
            filter['voucherId'] = self.editedVoucherId
        
        filter['show'] = self.showState[self.choiceShow.GetSelection()] 
        self.lc.refresh(filter)
        self.lc.SortListItems(0, 0)
        
    def OnBtnRefreshButton(self, event):
        self.refreshList()

    def OnBtnAutoAllocateButton(self, event):
        self.lc.autoAlloct(float(self.tcUnallocated.GetValue()))
        self.resetUnallocated()

    def OnBtnOKButton(self, event):
        #if(self.m_peer is None or self.getMoney() <= 0.0 or self.cb.GetValue() == ''):
        if(self.m_peer is None or self.cb.GetValue() == ''):
            dlg = wx.MessageDialog(self, u'业务数据不完整，请核对数据',u'提示',wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return
            
        unalloct = float(self.tcUnallocated.GetValue())
        if(unalloct < -0.001):
            msg = u'发生错误：分配金额大于收款金额，请重新设置分配金额'
            dlg = wx.MessageDialog(self, msg,u'提示',wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            return
        
##        if self.isModify():
##            msg = u'修改汇款单时请注意：\n--如果资金变动明细，关联此单会解除关系'
##            dlg = wx.MessageDialog(self, msg,u'提示',wx.OK|wx.ICON_INFORMATION)
##            dlg.ShowModal()
##            return
        
        try:
            dbmngr.dbmngr.beginTrans()
            
            if (self.isModify()):
                msg = u'确认保存修改后的信息？'
                dlg = wx.MessageDialog(self, msg,u'提示',wx.YES_NO|wx.ICON_QUESTION)
                if(dlg.ShowModal() == wx.ID_NO):
                    return
                
                self.deletePreVoucher()
            
            #raise NameError(u'test error')
            
            self.saveVoucher()
            self.saveFund()
            
            # if to create/modify voucher by accountDetail, then updateAccountDetail
            if self.accountDetailObj:
                self.updateAccountDetail()
            elif (self.checkAccount.GetValue()):
                self.makeAccountDetail()
        
            dbmngr.dbmngr.commitTrans()
            
        except Exception as e:
            dbmngr.dbmngr.rollbackTrans(e)
            
        #self.quit()
        self.btnOK.Enable(False)
        #if not self.accountDetailObj:
        #    self.btnMakeAccountDetail.Enable()

    def OnBtnCancelButton(self, event):
        self.doClose()

    def OnChoiceShowChoice(self, event):
        self.refreshList()

    def OnBtnMakeAccountDetailButton(self, event):
        if self.accountDetailObj:
            msg = u'资金变动明细中已包含该记录，只要保存该单据会自动更新'
            dlg = wx.MessageDialog(self, msg,u'提示',wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            return
        
        if self.makeAccountDetail():
            msg = u'添加成功，如果是银行账户，请注意消除与导入记录的重复'
        else:
            msg = u'添加出现问题，请联系开发者定位解决问题，以免影响使用'
            
        dlg = wx.MessageDialog(self, msg, u'提示', wx.OK|wx.ICON_INFORMATION)
        dlg.ShowModal()
        
        self.btnMakeAccountDetail.Enable(False)

    def OnBtnDayBeforeButton(self, event):
        day = self.dateBill.GetValue()        
        span = wx.DateSpan.Days(1)
        day.SubtractDS(span)
        self.dateBill.SetValue(day)
        self.dateCheck.SetValue(day)

    def OnBtnDayAfterButton(self, event):
        day = self.dateBill.GetValue()        
        span = wx.DateSpan.Days(1)
        day.AddDS(span)
        self.dateBill.SetValue(day)
        self.dateCheck.SetValue(day)

    def OnStLeftDclick(self, event):
        if (self.m_peer is None):
            return
        
        kit.getRootWin(self).showCustFund(self.m_peer)

